package org.example.trader.service;

import lombok.extern.slf4j.Slf4j;
import org.example.trader.api.TraderAPI;
import org.example.trader.data.entity.TraderEntity;
import org.example.trader.data.form.TraderInfoForm;
import org.example.trader.data.view.TraderInfo;
import org.example.trader.service.storage.TraderEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class TraderService implements TraderAPI {

    @Autowired
    private TraderEntityMapper traderEntityMapper;

    @Override
    public TraderInfo loginTrader(String account, String password) {

        TraderEntity traderEntity = traderEntityMapper.selectByAccountAndPassword(account, password);

        if(null == traderEntity){
            return null;

        }

        return transformTo(traderEntity);

    }

    @Override
    public TraderInfo addTrader(TraderInfoForm traderInfoForm) {

        TraderEntity traderEntity = transformFrom(traderInfoForm);

        Integer result = traderEntityMapper.insertTraderEntity(traderEntity);

        if(1 != result){
            return null;

        }

        TraderEntity updated = traderEntityMapper.selectTraderEntityById(traderEntity.getId());

        return transformTo(traderEntity);

    }

    @Override
    public TraderInfo updateTrader(TraderInfoForm traderInfoForm) {

        TraderEntity traderEntity = transformFrom(traderInfoForm);

        Integer result = traderEntityMapper.updateTraderEntity(traderEntity);

        if(1 != result){
            return null;

        }

        TraderEntity updated = traderEntityMapper.selectTraderEntityById(traderEntity.getId());

        return transformTo(updated);

    }

    private TraderEntity transformFrom(TraderInfoForm traderInfoForm){

        TraderEntity traderEntity = new TraderEntity();

        traderEntity.setId(traderInfoForm.getId());
        traderEntity.setAccount(traderInfoForm.getAccount());
        traderEntity.setPassword(traderInfoForm.getPassword());
        traderEntity.setDisplayName(traderInfoForm.getDisplayName());
        traderEntity.setState(traderInfoForm.getState());
        traderEntity.setCreateTimestamp(traderInfoForm.getCreateTimestamp());

        return traderEntity;

    }

    private TraderInfo transformTo(TraderEntity traderEntity){

        TraderInfo traderInfo = new TraderInfo();

        traderInfo.setId(traderEntity.getId());
        traderInfo.setDisplayName(traderEntity.getDisplayName());
        traderInfo.setState(traderEntity.getState());

        return traderInfo;

    }
}
